from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
from apps.users.models import User


def verify_email_url(user):
    s = Serializer(settings.SECRET_KEY, 600)
    data = {
        'user_id': user.id,
        'email': user.email
    }
    # 序列化参数
    token = s.dumps(data)

    verify_url = settings.EMAIL_VERIFY_URL + token.decode()

    return verify_url


def check_email_url(token):
    s = Serializer(settings.SECRET_KEY, 600)
    try:
        data = s.loads(token)
    except BadData:
        # token失效时
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoseNotExist:
            return None
        else:
            return user

